# -*- coding: utf-8 -*-
# @time:2025/4/4:21:32
# @IDE:PyCharm

from PIL import Image
import os
import sys
import tkinter as tk
from tkinter import messagebox


def open_file(file_path):
    try:
        if sys.platform == "win32":
            os.startfile(file_path)
        elif sys.platform == "darwin":
            os.system(f'open "{file_path}"')
        else:
            os.system(f'xdg-open "{file_path}"')
    except Exception as e:
        print(f"Info: Could not open file '{file_path}'. Error: {e}")
        messagebox.showwarning("打开文件", f"无法自动打开文件:\n{file_path}\n请手动打开。\n错误: {e}", parent=tk._default_root)


def _save_image(img, output_path, dpi, save_format):
    save_kwargs = {'dpi': (dpi, dpi)}
    img_to_save = img
    try:
        if save_format == 'jpg':
            save_kwargs['quality'] = 95
            if img_to_save.mode == 'RGBA' or img_to_save.mode == 'LA' or img_to_save.mode == 'P':
                if 'A' in img_to_save.getbands():
                    background = Image.new("RGB", img_to_save.size, (255, 255, 255))
                    try:
                        background.paste(img_to_save, mask=img_to_save.split()[-1])
                    except IndexError:
                        background.paste(img_to_save.convert('RGB'))
                    except ValueError:
                        if img_to_save.mode == 'LA':
                            img_rgb = img_to_save.convert('RGB')
                            alpha = img_to_save.split()[-1]
                            background.paste(img_rgb, mask=alpha)
                        else:
                            background.paste(img_to_save.convert('RGB'))
                    img_to_save = background
                elif img_to_save.mode != 'RGB':
                    img_to_save = img_to_save.convert('RGB')
        elif save_format == 'tiff':
            save_kwargs['compression'] = 'tiff_lzw'
        elif save_format == 'bmp':
            if 'A' in img_to_save.getbands():
                background = Image.new("RGB", img_to_save.size, (255, 255, 255))
                try:
                    background.paste(img_to_save, mask=img_to_save.split()[-1])
                except IndexError:
                    background.paste(img_to_save.convert('RGB'))
                except ValueError:
                    if img_to_save.mode == 'LA':
                        img_rgb = img_to_save.convert('RGB')
                        alpha = img_to_save.split()[-1]
                        background.paste(img_rgb, mask=alpha)
                    else:
                        background.paste(img_to_save.convert('RGB'))
                img_to_save = background
            elif img_to_save.mode != 'RGB':
                img_to_save = img_to_save.convert('RGB')
        if save_format in ['jpg', 'bmp'] and img_to_save.mode != 'RGB':
            print(f"Warning: Final conversion to RGB for saving as {save_format}")
            img_to_save = img_to_save.convert('RGB')
        img_to_save.save(output_path, **save_kwargs)
    except Exception as save_err:
        raise IOError(f"无法以 '{save_format}' 格式保存文件 '{os.path.basename(output_path)}': {save_err}")


def _handle_processing_error(error, context_filename):
    print(f"错误: 处理 {context_filename} 失败: {error}")
    if not messagebox.askyesno("处理错误", f"处理文件 '{context_filename}' 时出错:\n{error}\n\n是否继续处理剩余文件？", parent=tk._default_root):
        raise Exception("用户中止处理。")